<?php

class Model_Agilet_Template extends Model_Document
{
	protected $_collection = 'agilet_templates';

	function editElement($values)
	{
		if (isset($values['id']))
		{
			$id = $values['id'];
		}

		if (empty($id))
		{
			$id = 'e' . Helper_String::randomString(4, 1);
		}

		$elements = $this -> elements;

		$element = array(
			'id' => $id,
			'pid' => $values['pid'],
			'title' => $values['title'],
			'hl' => $values['hl'],
			'params' => array(),
			'type' => 'block',
			'position' => intval($values['position']),
			'area' => $values['area'],
			'active' => intval($values['active'])
		);

		$elements[$id] = $element;

		uasort($elements, function($a, $b)
		{
			return $a['position'] < $b['position'] ? -1 : 1;
		});

		$this -> _set('elements', $elements);
		return $this;
	}

	public function getStructure()
	{
		$elements = $this -> elements;

		$area = array();

		foreach ($elements as $k => $a)
		{
			$pk1 = isset($a['pid']) ? $a['pid'] : '';
			$pk2 = isset($elements[$pk1]) ? $elements[$pk1]['pid'] : '';
			$pk3 = isset($elements[$pk2]) ? $elements[$pk2]['pid'] : '';
			if ($pk3)
			{
				$elements[$pk1]['children'][$k] = $a;
				unset($elements[$k]);
			}
		}
		foreach ($elements as $k => $a)
		{
			$pk1 = isset($a['pid']) ? $a['pid'] : '';
			$pk2 = isset($elements[$pk1]) ? $elements[$pk1]['pid'] : '';
			if ($pk2)
			{
				$elements[$pk1]['children'][$k] = $a;
				unset($elements[$k]);
			}
		}
		foreach ($elements as $k => $a)
		{
			$pk1 = isset($a['pid']) ? $a['pid'] : '';
			if ($pk1)
			{
				$elements[$pk1]['children'][$k] = $a;
				unset($elements[$k]);
			}
		}

		foreach ($elements as $k => $a)
		{
			$pk1 = $a['pid'];
			if ($pk1 == '')
			{
				$area[$a['area']][] = $a;
			}
			unset($elements[$k]);
		}
		return array('area' => $area);
	}

}
